package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.model.Dictionary;
import com.neusoft.neuiotms.common.model.DictionaryType;
import com.neusoft.neuiotms.common.repository.DictionaryRepository;
import com.neusoft.neuiotms.common.repository.DictionaryTypeRepository;
import com.neusoft.neuiotms.dcam.common.model.QLocation;
import com.neusoft.neuiotms.dcam.common.model.QManufacturer;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.model.QAsset;
import com.neusoft.neuiotms.dcam.fixed.model.QAssetType;
import com.neusoft.neuiotms.dcam.fixed.model.QContract;
import com.neusoft.neuiotms.dcam.fixed.model.QMaintenance;
import com.neusoft.neuiotms.dcam.fixed.model.QProduct;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedAssetRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.JPQLQuery;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedAssetRepositoryImpl extends AbstractRepository implements CustomizedAssetRepository {
    @Autowired
    private DictionaryRepository dictionaryRepository;
    @Autowired
    private DictionaryTypeRepository dictionaryTypeRepository;

    @Override
    public List<Asset> search(final Searchable searchable) {
        final QAsset qAsset = QAsset.asset;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Asset> query = this.query().selectFrom(qAsset);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Long count(final Searchable searchable) {
        final QAsset qAsset = QAsset.asset;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Asset> query = this.query().selectFrom(qAsset);
        query.where(where);
        return query.fetchCount();
    }

    @Override
    public Page<Asset> search(final Pageable pageable, final Searchable searchable) {
        final QAsset qAsset = QAsset.asset;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Asset> query = this.query().selectFrom(qAsset);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QAsset qAsset = QAsset.asset;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qAsset.name, searchable, "name"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("code"))) {
            where.and(super.containsStr(qAsset.code, searchable, "code"));
        }
        // 资产codes集合
        final String[] codes = searchable.getStrArray("codes");
        if ((codes != null) && (codes.length > 0)) {
            where.and(super.inStrings(qAsset.code, searchable, "codes"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("manufacturerId"))) {
            where.and(super.equalsLong(qAsset.manufacturer.id, searchable, "manufacturerId"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("locationId"))) {
            where.and(super.equalsLong(qAsset.location.id, searchable, "locationId"));
        }
        // 厅局下属一级
        if (!StringUtils.isEmpty(searchable.getStrValue("secondDept"))) {
            where.and(super.equalsStr(qAsset.secondeDept, searchable, "secondDept"));
        }
        // 厅局下属二级
        if (!StringUtils.isEmpty(searchable.getStrValue("thirdDept"))) {
            where.and(super.equalsStr(qAsset.thirdDept, searchable, "thirdDept"));
        }

        // 位置code集合
        final String[] locationCodes = searchable.getStrArray("locationCodes");
        if ((locationCodes != null) && (locationCodes.length > 0)) {
            where.and(super.inStrings(qAsset.location.code, searchable, "locationCodes"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("locationCode"))) {
            where.and(super.equalsStr(qAsset.location.code, searchable, "locationCode"));
        }
        // 类型ID集合
        final String[] assetTypeCodes = searchable.getStrArray("assetTypeCodes");
        if ((assetTypeCodes != null) && (assetTypeCodes.length > 0)) {
            where.and(super.inStrings(qAsset.type.code, searchable, "assetTypeCodes"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("assetTypeId"))) {
            where.and(super.equalsLong(qAsset.type.id, searchable, "assetTypeId"));//类型code
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("assetTypeCode"))) {
            where.and(super.equalsStr(qAsset.type.code, searchable, "assetTypeCode"));//类型code
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("contractId"))) {
            where.and(super.equalsLong(qAsset.contract.id, searchable, "contractId"));//合同id
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("contractName"))) {
            where.and(super.containsStr(qAsset.contract.name, searchable, "contractName"));//合同名称
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("productId"))) {
            where.and(super.equalsLong(qAsset.product.id, searchable, "prodcutId"));//产品id
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("productName"))) {
            where.and(super.containsStr(qAsset.product.name, searchable, "productName"));//产品名称
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("userId"))) {
            where.and(super.equalsStr(qAsset.userId, searchable, "userId"));//用户
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("useDept"))) {
            where.and(super.containsStr(qAsset.useDept, searchable, "useDept"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("orgId"))) {
            where.and(super.containsStr(qAsset.orgId, searchable, "orgId"));
        }
        final String[] orgIds = searchable.getStrArray("orgIds");
        if ((orgIds != null) && (orgIds.length > 0)) {
            where.and(super.inStrings(qAsset.orgId, searchable, "orgIds"));
        }
        final String[] submmitTo = searchable.getStrArray("submmitTo");
        if ((submmitTo != null) && (submmitTo.length > 0)) {
            where.and(super.inStrings(qAsset.submmitTo, searchable, "submmitTo"));
        } else {
            where.and(super.inStrings(qAsset.belongTo, searchable, "-all"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("statusCode"))) {
            where.and(
                    super.equalsStr(qAsset.status, searchable, "statusCode"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("assetSource"))) {
            where.and(
                    super.equalsStr(qAsset.source, searchable, "assetSource"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("sequence"))) {
            where.and(super.containsStr(qAsset.sequence, searchable, "sequence"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("maintenanceUserId"))) {
            where.and(super.containsStr(qAsset.maintenance.maintenanceUserId, searchable, "maintenanceUserId"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("maintenanceNote"))) {
            where.and(super.containsStr(qAsset.maintenance.maintenanceNote, searchable, "maintenanceNote"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("measureUnit"))) {
            where.and(super.containsStr(qAsset.measureUnit, searchable, "measureUnit"));//属性值
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("money"))) {
            where.and(super.operateDouble(qAsset.money, searchable, "money"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("running"))) {
            where.and(super.containsStr(qAsset.running, searchable, "running"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("month"))) {
            where.and(super.equalsDouble(qAsset.month, searchable, "month"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("maintenanceStartBegin"))) {
            where.and(
                    super.afterOrEqualsDate(qAsset.maintenance.maintenanceStart, searchable, "maintenanceStartBegin"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("maintenanceStartEnd"))) {
            where.and(super.beforeOrEqualsDate(qAsset.maintenance.maintenanceStart, searchable, "maintenanceStartEnd"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("maintenanceEndBegin"))) {
            where.and(super.afterOrEqualsDate(qAsset.maintenance.maintenanceEnd, searchable, "maintenanceEndBegin"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("maintenanceEndEnd"))) {
            where.and(super.beforeOrEqualsDate(qAsset.maintenance.maintenanceEnd, searchable, "maintenanceEndEnd"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("submitTo"))) {
            where.and(super.containsStr(qAsset.submmitTo, searchable, "submitTo"));
        }
        if (null != searchable.getLongValue("start")) {
            where.and(super.afterOrEqualsDate(qAsset.usedate, searchable, "start"));
        }

        if (null != searchable.getLongValue("end")) {
            where.and(super.beforeOrEqualsDate(qAsset.usedate, searchable, "end"));
        }

        if (null != searchable.getLongValue("manufacturerEndDateStart")) {
            where.and(super.afterOrEqualsDate(qAsset.manufacturerEndDate, searchable, "manufacturerEndDateStart"));
        }

        if (null != searchable.getLongValue("manufacturerEndDateEnd")) {
            where.and(super.beforeOrEqualsDate(qAsset.manufacturerEndDate, searchable, "manufacturerEndDateEnd"));
        }

        if (searchable.hasKey("statusCodeIn")) {
            where.and(
                    super.inStrings(qAsset.status, searchable, "statusCodeIn"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("globalSearch"))) {
            final BooleanBuilder whereGlobal = new BooleanBuilder();
            final DictionaryType dictionaryType = this.dictionaryTypeRepository.findByType(DCAMConsts.ASSET_SOURCE);
            final List<Dictionary> source =
                    this.dictionaryRepository.findByDictionaryTypeOrderBySortAsc(dictionaryType);
            for (int i = 0; i < source.size(); i++) {
                if (source.get(i).getText().contains(searchable.getStrValue("globalSearch"))) {
                    searchable.put("source" + i, source.get(i).getCode());
                    whereGlobal.or(super.containsStr(qAsset.source, searchable, "source" + i));
                }
            }
            final DictionaryType dictionaryTypeStatus =
                    this.dictionaryTypeRepository.findByType(DCAMConsts.ASSET_STATUS);
            final List<Dictionary> status =
                    this.dictionaryRepository.findByDictionaryTypeOrderBySortAsc(dictionaryTypeStatus);
            for (int i = 0; i < status.size(); i++) {
                if (status.get(i).getText().contains(searchable.getStrValue("globalSearch"))) {
                    searchable.put("status" + i, status.get(i).getCode());
                    whereGlobal.or(super.containsStr(qAsset.status, searchable, "status" + i));
                }
            }
            // 厅局一级下属单位
            final DictionaryType secondType = this.dictionaryTypeRepository.findByType("secondDept");
            final List<Dictionary> seconds = this.dictionaryRepository.findByDictionaryTypeOrderBySortAsc(secondType);
            for (int i = 0; i < seconds.size(); i++) {
                if (seconds.get(i).getText().contains(searchable.getStrValue("globalSearch"))) {
                    searchable.put("second" + i, seconds.get(i).getCode());
                    whereGlobal.or(super.containsStr(qAsset.secondeDept, searchable, "second" + i));
                }
            }
            // 厅局二级下属单位
            final DictionaryType thirdType = this.dictionaryTypeRepository.findByType("thirdDept");
            final List<Dictionary> thirds = this.dictionaryRepository.findByDictionaryTypeOrderBySortAsc(thirdType);
            for (int i = 0; i < thirds.size(); i++) {
                if (thirds.get(i).getText().contains(searchable.getStrValue("globalSearch"))) {
                    searchable.put("third" + i, thirds.get(i).getCode());
                    whereGlobal.or(super.containsStr(qAsset.thirdDept, searchable, "third" + i));
                }
            }

            whereGlobal.or(super.containsStr(qAsset.measureUnit, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAsset.orgName, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAsset.userName, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAsset.sequence, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAsset.code, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAsset.name, searchable, "globalSearch"));

            final QMaintenance qMaintenance = QMaintenance.maintenance;
            final QAssetType qAssetType = QAssetType.assetType;
            final QContract qContract = QContract.contract;
            final QProduct qProduct = QProduct.product;
            final QLocation qLocation = QLocation.location;
            final QManufacturer qManufacturer = QManufacturer.manufacturer;

            final JPQLQuery<Long> reQuery = JPAExpressions.select(qAsset.id).from(qAsset)
                    .leftJoin(qMaintenance).on(qAsset.maintenance.id.eq(qMaintenance.id))
                    .leftJoin(qAssetType).on(qAsset.type.id.eq(qAssetType.id))
                    .leftJoin(qContract).on(qAsset.contract.id.eq(qContract.id))
                    .leftJoin(qProduct).on(qAsset.product.id.eq(qProduct.id))
                    .leftJoin(qLocation).on(qAsset.location.id.eq(qLocation.id))
                    .leftJoin(qManufacturer).on(qAsset.manufacturer.id.eq(qManufacturer.id));

            final BooleanBuilder likeWhere =
                    new BooleanBuilder()
                            .or(super.containsStr(qMaintenance.maintenanceNote, searchable, "globalSearch"))
                            .or(super.containsStr(qMaintenance.maintenanceUserName, searchable, "globalSearch"))
                            .or(super.containsStr(qMaintenance.maintenanceNote, searchable, "globalSearch"))
                            .or(super.containsStr(qAssetType.name, searchable, "globalSearch"))
                            .or(super.containsStr(qContract.name, searchable, "globalSearch"))
                            .or(super.containsStr(qProduct.name, searchable, "globalSearch"))
                            .or(super.containsStr(qLocation.name, searchable, "globalSearch"))
                            .or(super.containsStr(qAsset.submmitTo, searchable, "globalSearch"))
                            .or(super.containsStr(qManufacturer.name, searchable, "globalSearch"));

            reQuery.where(likeWhere);

            whereGlobal.or(qAsset.id.in(reQuery));
            where.and(whereGlobal);

        }
        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return Asset.class;
    }

}
